package io.renren.cos;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import io.renren.RenrenApplication;
import io.renren.config.TXYCosConfig;
import io.renren.modules.avanotes.dao.SubtitleDetailsDao;
import io.renren.modules.avanotes.dao.VocabularyDao;
import io.renren.modules.avanotes.entity.SubtitleDetailsEntity;
import io.renren.modules.avanotes.entity.VocabularyEntity;
import io.renren.modules.oss.cloud.COSCloudStorageService;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.oss.cloud.QcloudCloudStorageService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: xiaomi
 * @date: 2022/2/15
 * @description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RenrenApplication.class)
@Slf4j
public class QCloudUpload {

    @Autowired
    TXYCosConfig config;

    @Autowired
    SubtitleDetailsDao sdDao;

    @Autowired
    VocabularyDao vDao;

    @Autowired
    @Qualifier("calcPool")
    ThreadPoolExecutor calcPool;

    @Test
    public void putFiles() throws FileNotFoundException {
        QcloudCloudStorageService service = new QcloudCloudStorageService(config.getCConfig());
        String path = "E:\\File\\nginx-1.14.2\\html\\resource\\voice\\a\\a bas.wav";
        service.upload(new FileInputStream(path), "a bas.wav");
    }

    @Test
    public void putFileSample() {
        CloudStorageConfig config = this.config.getCConfig();
        // 1 初始化用户身份信息（secretId, secretKey）。
// SECRETID和SECRETKEY请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        String secretId = config.getQcloudSecretId();
        String secretKey = config.getQcloudSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(config.getQcloudRegion());
        ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        String path = "E:\\File\\nginx-1.14.2\\html\\resource\\voice\\a\\a bas.wav";
        // 指定要上传的文件
        File localFile = new File(path);
// 指定文件将要存放的存储桶
        String bucketName = config.getQcloudBucketName();
// 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = "exampleobject";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
    }

    /**
     * 单线程版本上传资源到 COS
     */
    @Test
    public void putMovies() {
        COSCloudStorageService service = new COSCloudStorageService(config.getCConfig());
        List<SubtitleDetailsEntity> list = sdDao.selectList(new QueryWrapper<SubtitleDetailsEntity>().eq(SubtitleDetailsEntity.CN_STATUS, 1));
        for (SubtitleDetailsEntity entity : list) {
            SubtitleDetailsEntity updater = new SubtitleDetailsEntity();
            updater.setId(entity.getId());

            String path = entity.getPath().replace("E:\\File\\", "E:\\File\\nginx-1.14.2\\html\\resource\\");
            String key = entity.getPath().replace("E:\\File\\", "").replace("\\", "/");
            try {
                String finalKey = service.upload(path, key);
                //上传成功
                updater.setStatus(2);
                updater.setCoskey(finalKey);
            } catch (Exception e) {
                updater.setStatus(-2);
            } finally {
                sdDao.updateById(updater);
            }
        }
    }

    /**
     * 通过多线程上传资源
     */
    @Test
    public void putMoviesByMultiThreads() {

        COSCloudStorageService service = new COSCloudStorageService(config.getCConfig());
        List<SubtitleDetailsEntity> list = sdDao.selectList(new QueryWrapper<SubtitleDetailsEntity>().eq(SubtitleDetailsEntity.CN_STATUS, 1));
        for (SubtitleDetailsEntity entity : list) {
            calcPool.execute(() -> {
                SubtitleDetailsEntity updater = new SubtitleDetailsEntity();
                updater.setId(entity.getId());

                String path = entity.getPath().replace("E:\\File\\", "E:\\File\\nginx-1.14.2\\html\\resource\\");
                String key = entity.getPath().replace("E:\\File\\", "").replace("\\", "/");
                try {
                    String finalKey = service.upload(path, key);
                    //上传成功
                    updater.setStatus(2);
                    updater.setCoskey(finalKey);
                } catch (Exception e) {
                    updater.setStatus(-2);
                } finally {
                    sdDao.updateById(updater);
                }
            });
        }
        while (true) {

        }
    }

    /**
     * 更新音频链接
     */
    @Test
    public void putVocabularyByMultiThreads() {
        COSCloudStorageService service = new COSCloudStorageService(config.getCConfig());
        List<VocabularyEntity> list = vDao.selectList(new QueryWrapper<VocabularyEntity>().ne(VocabularyEntity.CN_PRONUNCIATION_RELATIVE_PATH, ""));
        for (VocabularyEntity entity : list) {
            calcPool.execute(() -> {
                VocabularyEntity updater = new VocabularyEntity();
                updater.setId(entity.getId());

                String path = "E:\\File\\nginx-1.14.2\\html\\resource\\" + entity.getPronunciationRelativePath();
                String key = entity.getPronunciationRelativePath().replace("\\", "/");
                try {
                    String finalKey = service.upload(path, key);
                    //上传成功
                    updater.setCoskey(finalKey);
                    vDao.updateById(updater);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {

                }
            });
        }
        while (true) {

        }
    }
}
